﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using ARS.PublicTool;

namespace ARS.Control.Common.EntityManage
{
    /// <summary>
    /// 实体转换sql语句
    /// </summary>
    public class EntityToSql:BaseModel
    {
        protected EntityTableInfo _tableInfo;
//        public List<ARS.Control.Custom.Entity.Fields.Field> FieldList =
//            new List<ARS.Control.Custom.Entity.Fields.Field>();
        public EntityToSql(object Model, EntityTableInfo tableInfo)
        {
            base.Model = Model;
            base.typeModel = Model.GetType();
            this._tableInfo = tableInfo;
        }

        /// <summary>
        /// 获取插入语言
        /// </summary>
        /// <param name="typeModel"></param>
        /// <param name="Model"></param>
        /// <returns></returns>
        public string GetAddSql()
        {
            System.Text.StringBuilder sb = new StringBuilder();
            sb.Append("insert into ");
            sb.Append(this._tableInfo.TableName);
            sb.Append(" ( ");

            StringBuilder sb_attr = new StringBuilder();
            StringBuilder sb_value = new StringBuilder();

            object value;
            foreach (PropertyInfo pi in typeModel.GetProperties())
            {
                if (pi.Name == this._tableInfo.KeyInfo.Key)
                {
                    continue;
                }
                value = pi.GetValue(Model, null);
                if (value == null || string.IsNullOrEmpty(value.ToString()))
                {
                    continue;
                }
                sb_attr.Append(pi.Name);
                sb_attr.Append(",");

                sb_value.Append(string.Format("'{0}',", value));
                //sb_value.Append(",");
            }
            sb_attr.Remove(sb_attr.Length - 1, 1);
            sb_value.Remove(sb_value.Length - 1, 1);

            sb.Append(sb_attr);
            sb.Append(") ");

            sb.Append(" values (");
            sb.Append(sb_value);
            sb.Append(")");//SELECT @@IDENTITY
            return sb.ToString();
        }

        //private EntityTableInfo _entityTableInfo = new EntityTableInfo();
        /// <summary>
        /// 获取添加sql语句
        /// </summary>
        /// <returns></returns>
        public string GetAddSqlParams( List<ARS.Control.Custom.Entity.Forms.Form> controls)
        {


            StringBuilder sbColumns = new StringBuilder();
            StringBuilder sbValues = new StringBuilder();

            //var controls = this._tableInfo.ControlsUpdate;
            //parameters = this._tableInfo.GetParameters(controls);
            foreach (var control in controls)
            {
                var item = control.Field;
                if (item.Value == null)
                {
                    //continue;
                }
                sbColumns.Append(item.Db_Field_Name).Append(",");
                sbValues.Append(Control.Factory.DbFactory.CreateDbParmCharacter()).Append(item.Db_Field_Name).Append(",");
            }

            //foreach (var item in _tableInfo.ColumnItemList)
            //{
            //    if (!string.IsNullOrEmpty(item.Remark))
            //    {
            //        //Object value = _tableInfo.EntityColumnInfoList[KeyField];

            //    }
            //}

            return GetAddSqlParams(sbColumns, sbValues);
        }

        protected string GetAddSqlParams(StringBuilder sbColumns, StringBuilder sbValues)
        {
            if (sbColumns.Length > 0 && sbValues.Length > 0)
            {
                sbColumns.Remove(sbColumns.Length - 1, 1);
                sbValues.Remove(sbValues.Length - 1, 1);
            }
            else
            {
                return null;
                //throw new Exception("没有需要添加的数据");
            }
            string getnewId;
            if (DataBase.Provider.DbFactory.DbTypeIsSqlServer())
            {
                getnewId = "select @@IDENTITY";
            }
            else if (DataBase.Provider.DbFactory.DbTypeIsMySql())
            {
                getnewId = "select last_insert_id()";
            }
            else
            {
                getnewId = "";
            }
            return string.Format("INSERT INTO {0}({1}) VALUES({2});{3}", _tableInfo.TableName, sbColumns, sbValues, getnewId);
        }

        /// <summary>
        /// 获取更新的sql
        /// </summary>
        /// <param name="typeModel"></param>
        /// <param name="Model"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetUpdateSql()
        {
            System.Text.StringBuilder sb = new StringBuilder();
            sb.Append("update ");
            sb.Append(this._tableInfo.TableName);
            sb.Append(" set ");
            foreach (PropertyInfo pi in typeModel.GetProperties())
            {
                if (pi.Name == this._tableInfo.KeyInfo.Key)
                {
                    continue;
                }
                if (pi.GetValue(Model, null) == null)
                {
                    continue;
                }
                sb.Append(string.Format("{0}='{1}',", pi.Name, pi.GetValue(Model, null)));
            }
            sb.Remove(sb.Length - 1, 1);
            sb.Append(" where ");
            sb.Append(string.Format("{0}={1}", this._tableInfo.KeyInfo.Key, ReflectionHelper.GetObjAttrValue(typeModel, this._tableInfo.KeyInfo.Key, Model)));
            return sb.ToString();
        }

        public string GetUpdateSqlParams(List<ARS.Control.Custom.Entity.Forms.Form> controls)
        {
            return this.GetUpdateSqlParams(controls, null);
        }

        public string GetUpdateSqlParams(List<ARS.Control.Custom.Entity.Forms.Form> controls,string where)
        {
            StringBuilder sb = new StringBuilder();

            //var controls = this._tableInfo.ControlsAdd;
            //parameters = this._tableInfo.GetParameters(controls);
            foreach (var control in controls)
            {
                var item = control.Field;
                if (item.Value == null)
                {
                    //continue;
                }
                sb.Append(item.Db_Field_Name).Append("=").Append(Control.Factory.DbFactory.CreateDbParmCharacter() + item.Db_Field_Name).Append(",");
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
            }
            else
            {
                return null;
            }
            if (where == null)
            {
                return string.Format("update {0} set {1} where {2} = {3};select {3}", _tableInfo.TableName, sb,
                    _tableInfo.KeyInfo.Key, this._tableInfo.KeyInfo.Value);
            }
            else
            {
                return string.Format("update {0} set {1} where {2};select {3}", _tableInfo.TableName, sb, where, this._tableInfo.KeyInfo.Value);
            }
        }
        /// <summary>
        /// 获取
        /// </summary>
        /// <returns></returns>
        public string GetAddOrUpdateSql()
        {
            bool flag;
            return GetAddOrUpdateSql(out flag);
        }

        /// <summary>
        /// 获取插入或跟新的sql
        /// </summary>
        /// <param name="typeModel"></param>
        /// <param name="Model"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetAddOrUpdateSql(out bool isAdd)
        {
            object keyValue = ReflectionHelper.GetObjAttrValue(typeModel, this._tableInfo.KeyInfo.Key, Model);
            if (keyValue == null || keyValue.ToString() == "0" || keyValue.ToString() == "")
            {
                isAdd = true;
                return this.GetAddSql();
            }
            else
            {
                isAdd = false;
                return this.GetUpdateSql();
            }
        }

        //public string GetAddOrUpdateSqlParams(out bool isAdd)
        //{
        //    object keyValue = ReflectionHelper.GetObjAttrValue(TypeModel, this._tableInfo.KeyInfo.KeyField, Entity);
        //    if (keyValue == null || keyValue.ToString() == "0" || keyValue.ToString() == "")
        //    {
        //        isAdd = true;
        //        return this.GetAddSqlParams();
        //    }
        //    else
        //    {
        //        isAdd = false;
        //        return this.GetUpdateSqlParams();
        //    }
        //}

        /// <summary>
        /// 获取查询的sql
        /// </summary>
        /// <param name="typeModel"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetSelectSql()
        {
            return GetSelectSqlFields("*");
            //System.Text.StringBuilder sb = new StringBuilder();
            //sb.Append("select * from ");
            //sb.Append(this._tableInfo.TableName);
            //sb.Append(string.Format(" where {0}={1}", this._tableInfo.KeyInfo.Key,this._tableInfo.KeyInfo.Value));
            //return sb.ToString();
        }

        public string GetSelectSqlFields(string fieldList,string where=null)
        {
            System.Text.StringBuilder sb = new StringBuilder();
            sb.Append("select ");
            sb.Append(fieldList);
            sb.Append(" from ");
            //sb.Append("select * from ");
            sb.Append(this._tableInfo.TableName);
            if (where == null)
            {
                sb.Append(string.Format(" where {0}={1}", this._tableInfo.KeyInfo.Key, this._tableInfo.KeyInfo.Value));

            }
            else
            {
                sb.Append(string.Format(" where {0}", where));
            }
            return sb.ToString();
        }

        /// <summary>
        /// 获取查询的sql
        /// </summary>
        /// <param name="typeModel"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetSelectSql(string where)
        {
            return GetSelectSqlFields("*", where);
            //System.Text.StringBuilder sb = new StringBuilder();
            //sb.Append("select * from ");
            //sb.Append(this._tableInfo.TableName);
            //sb.Append(string.Format(" where {0}", where));
            //return sb.ToString();
        }


        /// <summary>
        /// 获取删除的语句
        /// </summary>
        /// <returns></returns>
        public string GetDeleteSql()
        {
            return "delete from where Id=";
        }


        public string GetUpdateSqlParams<T>(List<T> controls) where T : ARS.Control.Custom.Entity.Fields.Field
        {
            return this.GetUpdateSqlParams(controls, null);
        }

        public string GetUpdateSqlParams<T>(List<T> fields, string where) where T : ARS.Control.Custom.Entity.Fields.Field
        {
            StringBuilder sb = new StringBuilder();

            //var controls = this._tableInfo.ControlsAdd;
            //parameters = this._tableInfo.GetParameters(controls);
            foreach (var control in fields)
            {
                var item = control;
                if (item.Value == null)
                {
                    //continue;
                }
                sb.Append(item.Db_Field_Name).Append("=").Append(ARS.Control.Factory.DbFactory.CreateDbParmCharacter() + item.Db_Field_Name).Append(",");
            }
            if (sb.Length > 0)
            {
                sb.Remove(sb.Length - 1, 1);
            }
            else
            {
                return null;
            }
            if (where == null)
            {
                return string.Format("update {0} set {1} where {2} = {3};select {3}", _tableInfo.TableName, sb,
                    _tableInfo.KeyInfo.Key, this._tableInfo.KeyInfo.Value);
            }
            else
            {
                return string.Format("update {0} set {1} where {2};select {3}", _tableInfo.TableName, sb, where, this._tableInfo.KeyInfo.Value);
            }
        }

        /// <summary>
        /// 获取添加sql语句
        /// </summary>
        /// <returns></returns>
        //        public string GetAddSqlParams(List<ARSWpf.Control.Custom.Entity.Forms.Form> controls)
        //        {
        //            StringBuilder sbColumns = new StringBuilder();
        //            StringBuilder sbValues = new StringBuilder();
        //            foreach (var control in controls)
        //            {
        //                var item = control.Field;
        //                if (item.Value == null)
        //                {
        //                    //continue;
        //                }
        //                sbColumns.Append(item.Db_Field_Name).Append(",");
        //                sbValues.Append(ARS.Control.Factory.DbFactory.CreateDbParmCharacter()).Append(item.Db_Field_Name).Append(",");
        //            }
        //            return GetAddSqlParams(sbColumns, sbValues);
        //        }

        public string GetAddSqlParams<T>(List<T> controls) where T : ARS.Control.Custom.Entity.Fields.Field
        {
            StringBuilder sbColumns = new StringBuilder();
            StringBuilder sbValues = new StringBuilder();
            foreach (var control in controls)
            {
                var item = control;
                if (item.Value == null)
                {
                    //continue;
                }
                sbColumns.Append(item.Db_Field_Name).Append(",");
                sbValues.Append(ARS.Control.Factory.DbFactory.CreateDbParmCharacter()).Append(item.Db_Field_Name).Append(",");
            }
            return GetAddSqlParams(sbColumns, sbValues);
        }

        //public void GetSelectSqlSingle()
        //{
        //    StringBuilder sb = new StringBuilder();
        //    foreach (var form in this._tableInfo.FormControls)
        //    {

        //    }
        //}
        public void GetSelectSqlExists()
        {

        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <returns></returns>
        public string GetDeleteSql(string where)
        {
            return string.Format("delete from {0} where {1}", _tableInfo.TableName, where);
        }

        public string GetDeleteKey<T>(T id)
        {
            return string.Format("delete from {0} where {1}={2}", _tableInfo.TableName, _tableInfo.KeyInfo.Key, id);
        }


    }
}
